﻿(function () {
    var dbName = "CalendarDB";
    var isNew = false;

    function log(message) {
        //var logdiv = document.getElementById("dblog");
        //logdiv.innerText = message;
    }

    WinJS.Namespace.define("CalenderDB", {
        createDB: function() {
            // Create the request to open the database, named CalendarNoteDB. If it doesn't exist, create it and immediately
            // upgrade to version 1.
            var dbRequest = window.indexedDB.open(dbName, 1);

            // Add asynchronous callback functions
            dbRequest.onerror = function () {
                log("db create request error");
            };
            dbRequest.onsuccess = function (evt) {

                if (!isNew) {
                    log("db already exist");
                }
                else {
                    log("db create request success");
                }
                evt.target.result.close();
            };
            dbRequest.onupgradeneeded = function (evt) {
                var sampledata = { title: "the event title", date: "20130102", content: "the event content", isNotify: true };
                // Get the version update transaction handle, since we want to create the schema as part of the same transaction.
                var txn = evt.target.transaction;

                // Create the note object store, with an index on the book title. Note that we set the returned object store to a variable
                // in order to make further calls (index creation) on that object store.
                var noteStore = evt.target.result.createObjectStore("Notes", { keyPath: "id", autoIncrement: true });
                noteStore.createIndex("IndexByTitle", "title", { unique: false });
                noteStore.createIndex("IndexByDate", "date", { unique: false });


                var addResult = noteStore.add(sampledata);

                // Once the creation of the object stores is finished (they are created asynchronously), log success.
                txn.oncomplete = function () {
                    log("Database schema created.");
                    txn.db.close();
                };

                isNew = true;
            };
            dbRequest.onblocked = function () {
                log("db create request blocked");
            };

            isNew = false;
        },
        deleteDB: function () {
            var dbRequest = window.indexedDB.deleteDatabase(dbName);
            dbRequest.onerror = function () {
                log("Error deleting database.");
            };
            dbRequest.onsuccess = function () {
                log("db deleted");
                var outputDiv = document.getElementById("dbcontent");
                outputDiv.innerHTML = "";
            };
            dbRequest.onblocked = function () {
                log("Database delete blocked.");
            };
        },
        writeData: function (data, targetPage) {
            var dbRequest = window.indexedDB.open(dbName, 1);
            dbRequest.onsuccess = function (evt) {
                if (evt.target.result.objectStoreNames.length < 1) {
                    log("Database schema does not exist, create db first")
                    return;
                }

                // Create a transaction to write the changes to the database        
                var txn = evt.target.result.transaction(["Notes"], "readwrite");

                // Set the event callbacks for the transaction
                txn.onerror = function (evt) { log("Error writing data."); };
                txn.onabort = function (evt) { log("Writing of data aborted."); };

                // The oncomplete event handler is called asynchronously once all writes have completed; when that's done, we reset our pending write queue.
                txn.oncomplete = function () {
                    // pendingWrites = [];
                    log("Changes saved to database.");
                    //readData();
                    WinJS.Navigation.navigate(targetPage);
                    txn.db.close();
                };

                var noteStore = txn.objectStore("Notes");

                var addResult = noteStore.add(data);
                addResult.onerror = function (evt) { log("Error adding data."); }
            }
        },
        readData: function (dataToOutput) {
            var dbRequest = window.indexedDB.open(dbName, 1);
            dbRequest.onsuccess = function (evt) {
                if (evt.target.result.objectStoreNames.length < 1) {
                    log("no read, Database schema does not exist, create db first")
                    evt.target.result.close();
                    return;
                }

                // Declare arrays to hold the data to be read.
                var notes = [];
                var txn = evt.target.result.transaction(["Notes"], "readonly");

                // Set the event callbacks for the transaction.
                txn.onerror = function () { log("Error reading data."); };
                txn.onabort = function () { log("Reading of data aborted."); };

                // The oncomplete event handler is called asynchronously once reading is finished and the data arrays are fully populated. This
                // completion event will occur later than the cursor iterations defined below, because the transaction will not complete until
                // the cursors are finished.
                txn.oncomplete = function () {
                    var outputContent = "";

                    // If there are no notes to display, there is no need to continue.
                    var len = notes.length;
                    if (len === 0) {
                        return;
                    }

                    // Construct an output table with one row per book.
                    for (i = 0; i < len; i++) {
                        outputContent += "<div>title:" + notes[i].title + ",date:" + notes[i].date + ",isNotify:" + notes[i].isNotify + "</div>";
                        //document.getElementById(notes[i].date).parentElement.parentElement.className = "event";
                    }

                    // Display the content.
                    //var outputDiv = document.getElementById("dbcontent");
                    if (dataToOutput) {
                        dataToOutput.innerHTML = outputContent;
                    }

                    var badgeContent = new NotificationsExtensions.BadgeContent.BadgeNumericNotificationContent(len);
                    Windows.UI.Notifications.BadgeUpdateManager.createBadgeUpdaterForApplication().update(badgeContent.createNotification());

                    var notificationManager = Windows.UI.Notifications.ToastNotificationManager;
                    var ToastContent = NotificationsExtensions.ToastContent;
                    var content = ToastContent.ToastContentFactory.createToastImageAndText01();
                    content.launch = '{"data":"datacontent"}';
                    content.textBodyWrap.text = notes[0].title;
                    content.image.src = "images/toast_184x184.png";
                    content.image.alt = "alt text";
                    content.audio.content = ToastContent.ToastAudioContent.default;
                    //content.duration = ToastContent.ToastDuration.long;
                    //content.audio.loop = true;

                    var toast = content.createNotification();
                    toast.addEventListener("dismissed", function (e) {
                        switch (e.reason) {
                            case Windows.UI.Notifications.ToastDismissalReason.applicationHidden:
                                //WinJS.log && WinJS.log("The application hid the toast using toastNotifier.hide()", "sample", "status");
                                break;
                            case Windows.UI.Notifications.ToastDismissalReason.userCanceled:
                                //WinJS.log && WinJS.log("The user dismissed this toast", "sample", "status");
                                break;
                            case Windows.UI.Notifications.ToastDismissalReason.timedOut:
                                //WinJS.log && WinJS.log("The toast has timed out", "sample", "status");
                                break;
                        }
                    }, false);

                    toast.addEventListener("failed", function (e) {
                        //WinJS.log && WinJS.log("The toast encountered an error", "sample", "error");
                    }, false);

                    notificationManager.createToastNotifier().show(toast);

                    txn.db.close();
                };

                // Create a cursor on the notes object store. Because we want the results to be returned in title order, we use the title index
                // on the object store for the cursor to operate on. We could pass a keyRange parameter to the openCursor call to filter the cursor
                // to specific titles.
                //var noteCursorRequest = txn.objectStore("Notes").index("title").openCursor();
                var noteObjectStore = txn.objectStore("Notes");

                //var boundKeyRange = IDBKeyRange.lowerBound("app", true);
                //var noteCursorRequest = noteObjectStore.index("IndexByTitle").openCursor(boundKeyRange, "next");
                var noteCursorRequest = noteObjectStore.index("IndexByTitle").openCursor();

                var oGetInex = noteObjectStore.index("IndexByTitle");
                var oGet = oGetInex.get("app");
                oGet.onsuccess = function (e) {
                    var o = e.target.result;
                }
                //var oIndexApp = noteObjectStore.index("app");
                var oCount = noteObjectStore.count();
                oCount.onsuccess = function (e) {
                    var r = e.target.result;
                }

                // As each record is returned (asynchronously), the cursor calls the onsuccess event; we store that data in our notes array
                noteCursorRequest.onsuccess = function (e) {
                    var cursor = e.target.result;
                    if (cursor) {
                        notes.push(cursor.value);
                        cursor.continue();
                    }
                };
            };
        }
        
    });

})();